package com.itbaizhan.springsecuritydemo.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Service
public class MyAuthorizationService {
    //自定义访问控制逻辑，返回值为是否可访问资源
    public boolean hasPermission(HttpServletRequest request, Authentication authentication){
        //获取认证的用户
        UserDetails userDetails =(UserDetails) authentication.getPrincipal();
        //获取登录用户的权限
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        //获取请求的URL
        String uri = request.getRequestURI();
        //将URL封装为权限对象
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(uri);
        //判断用户的权限集合中是否包含请求的URL权限对象    请求的url权限是否在用户的权限中
        return authorities.contains(grantedAuthority);
    }

}
